<?php
/**
 * Description of Class_Team
 *
 * @author Fantastik78
 */

class Team {

    private $team_name = "team_name";
    private $team_description = "team_description";
    private $team_name_trim;
    private $team_description_trim;

    //ERRORS
        //createTeam Function
        private $e_team_name_empty = false;
        private $e_team_name_null = false;
        private $e_team_name_exist = false;
        private $e_team_desciption_empty = false;
        private $e_team_desciption_null = false;
        //addUser Function
        private $e_no_user = false;
        //useSerial Function
        private $e_no_serial = false;
        private $e_alrdy_add = false;


    private function verifEmail($email){
        if(preg_match('/^[a-zA-Z0-9\._-]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,6}$/', $email) == 1){
            return true;
        }else{
            return false; ;
        }
    }

    public function getErrorsCreateTeam(){
         if(isset($_POST['btn_valider_team'])){
             if($this->e_team_name_empty || $this->e_team_name_null){echo "Vous devez préciser un nom d'equipe de travail." ;}
             if($this->e_team_name_exist){echo "Le nom de l'equipe de travail existe déjà." ;}
             if($this->e_team_desciption_empty || $this->e_team_desciption_null){echo "Vous devez préciser une description de l'equipe de travail." ;}
         }
    }

    public function createTeam(){
        if(isset($_POST['btn_valider_team'])){
            $post_secu = array_map("mysql_real_escape_string", $_POST);
            if(!empty($post_secu[$this->team_name])){
                $this->team_name_trim = trim($post_secu[$this->team_name]);
                if($this->team_name_trim != null){
                    $query = mysql_query("SELECT COUNT(*) as exist FROM team WHERE team_name='" . $post_secu[$this->team_name] . "'");
                    $result_query = mysql_fetch_array($query);
                    if($result_query['exist'] == 0){
                        if(!empty($post_secu[$this->team_description])){
                            $this->team_description_trim = trim($post_secu[$this->team_description]);
                            if($this->team_description_trim != null){
                                mysql_query("INSERT INTO team (team_name, team_description, serial) VALUES  ('" . $post_secu[$this->team_name] . "', '" . $post_secu[$this->team_description] . "', '".Member::getUniqueKey(25)."')");
                                $team_id = mysql_insert_id();
                                mysql_query("INSERT INTO team_member (team_id, member_id) VALUES ('" . $team_id . "', '" . $_SESSION['member_session']['id'] . "')");

                                $admin = mysql_query("SELECT COUNT(*) as nbright FROM group_right WHERE dashbd_add='1' AND todo_add='1' AND todo_edit='1' AND todo_del='1' AND ideabox_read='1' AND ideabox_add='1' AND ideabox_edit='1' AND ideabox_del='1' AND files_read='1' AND files_add='1' AND files_edit='1' AND files_del='1' AND files_dl='1' AND files_ul='1' AND msg_read='1' AND msg_add='1' AND msg_edit='1' AND msg_del='1'")or die("Could not perform select query - " . mysql_error());
                                $fetch_admin = mysql_fetch_array($admin);

                                if($fetch_admin['nbright'] == 0){
                                        mysql_query("INSERT INTO group_right (dashbd_add, todo_add, todo_edit, todo_del, ideabox_read, ideabox_add, ideabox_edit, ideabox_del, files_read, files_add, files_edit, files_del, files_dl, files_ul, msg_read, msg_add, msg_edit, msg_del) VALUES ('1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1')");
                                        $rightid = mysql_insert_id();
                                        mysql_query("INSERT INTO team_group (name_group, team_id, right_id) VALUES ('Administrateur', '" . $team_id . "', '" . $rightid . "')");
                                        mysql_query("INSERT INTO member_group (group_id, member_id) VALUES ('" . mysql_insert_id() . "', '" . $_SESSION['member_session']['id']  . "')");
                                }else{
                                mysql_query("INSERT INTO team_group (name_group, team_id, right_id) VALUES ('Administrateur', '" . $team_id . "', '" . $fetch_admin['nbright'] . "')");
                                mysql_query("INSERT INTO member_group (group_id, member_id) VALUES ('" . mysql_insert_id() . "', '" . $_SESSION['member_session']['id']  . "')");
                                }
                                
                                $query2 = mysql_query("SELECT COUNT(*) as nbright, id FROM group_right WHERE dashbd_add='0' AND todo_add='0' AND todo_edit='0' AND todo_del='0' AND ideabox_read='0' AND ideabox_add='0' AND ideabox_edit='0' AND ideabox_del='0' AND files_read='0' AND files_add='0' AND files_edit='0' AND files_del='0' AND files_dl='0' AND files_ul='0' AND msg_read='0' AND msg_add='0' AND msg_edit='0' AND msg_del='0'");
                                $res2 = mysql_fetch_array($query2);
                                
                                if($res2['nbright'] == 0){
                                    mysql_query("INSERT INTO group_right (dashbd_add, todo_add, todo_edit, todo_del, ideabox_read, ideabox_add, ideabox_edit, ideabox_del, files_read, files_add, files_edit, files_del, files_dl, files_ul, msg_read, msg_add, msg_edit, msg_del) VALUES ('0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0')");
                                    $rightid_default = mysql_insert_id();
                                }else{
                                    $rightid_default = $res2['id'];
                                }
                                mysql_query("INSERT INTO team_group (name_group, team_id, right_id) VALUES ('Default', '".$team_id."' , '".$rightid_default."')");                                    
                                
                                return true;
                            }else{
                                $this->e_team_desciption_null = true;
                            }
                        }else{
                            $this->e_team_desciption_empty = true;
                        }
                    }else{
                        $this->e_team_name_exist = true;
                    }
                }else{
                    $this->e_team_name_null = true;
                }
            }else{
                $this->e_team_name_empty = true;
            }
        }
    }



    public function sendInvitation(){
        if(isset($_POST['btn_add_mbr'])){
            $secu_post = array_map("mysql_real_escape_string", $_POST);

            $loop = true;
            $i = 1;
                if(!empty($secu_post['new_user'])){
                    if(!$this->verifEmail($secu_post['new_user'])){
                        $query = mysql_query("SELECT id_member FROM member WHERE pseudo='" . $secu_post['new_user'] . "'");
                        $nbre_row = mysql_num_rows($query);
                        $member = mysql_fetch_array($query);
                        $query_already_inv = mysql_query("SELECT id FROM team_invitation WHERE guest='" . $member['id_member'] . "' AND team='" . $_SESSION['member_session']['team'] . "'");
                        $nber_alrd_exist = mysql_num_rows($query_already_inv);
                        $query_alrd_inv = mysql_query("SELECT id FROM team_member WHERE member_id='" . $member['id_member'] . "' AND team_id='" . $_SESSION['member_session']['team'] . "'");
                        $nber_member_exist = mysql_num_rows($query_alrd_inv);
                        if($nber_alrd_exist == 0 && $nber_member_exist == 0){
                            
                            if($nbre_row == 1){
                                $query = mysql_query("INSERT INTO team_invitation (guest, host, team) VALUES ('" . $member['id_member'] . "', '" . $_SESSION['member_session']['id'] . "', '" . $_SESSION['member_session']['team'] . "')");
                                $loop = false;
                            }else{
                                echo "Le membre n'est pas présent dans notre base de donnée. Entrer son mail pour lui que nous lui envoyons une invitation.";
                                $this->e_no_user = true;
                                $loop = false;
                            }
                        }else{
                            echo "Invitation déja envoyé.";
                        }
                        
                    }else{
                        $query = mysql_query("SELECT id_member FROM member WHERE mail='" . $secu_post['new_user'] . "'");
                        $nbre_row = mysql_num_rows($query);
                        $member = mysql_fetch_array($query);
                        $query_already_inv = mysql_query("SELECT * FROM team_invitation WHERE guest='" . $member['id_member'] . "' AND team='" . $_SESSION['member_session']['team'] . "'");
                        $nber_alrd_exist = mysql_num_rows($query_already_inv);
                        $query_alrd_inv = mysql_query("SELECT id FROM team_member WHERE member_id='" . $member['id_member'] . "' AND team_id='" . $_SESSION['member_session']['team'] . "'");
                        $nber_member_exist = mysql_num_rows($query_alrd_inv);
                        if($nber_alrd_exist == 0 && $nber_member_exist == 0){
                            if($nbre_row == 1){
                                $query = mysql_query("INSERT INTO team_invitation (guest, host, team) VALUES ('" . $member['id_member'] . "', '" . $_SESSION['member_session']['id'] . "', '" . $_SESSION['member_session']['team'] . "')");
                                $loop = false;
                            }else{
                                echo "Le membre n'est pas présent dans notre base de donnée. Envoi d'un email a son addresse";
                                $loop = false;
                            }
                        }else{
                            echo "Invitation déja envoyé.";
                        }
                    }
                    $i++;
                }else{
                    $loop = false;
                }
        }
    }
    
    public function getSerial(){
        if(isset($_SESSION['member_session']['team'])){
            $query = mysql_query("SELECT serial FROM team WHERE id_team='".$_SESSION['member_session']['team']."'");
            $res = mysql_fetch_array($query);
            return $res['serial'];
        }
    }
    
    public function getErrorsUseSerial(){
        if(isset($_POST['btn_serial'])){
            if($this->e_alrdy_add){ echo "Vous faites déjà parti de ce projet.<br/>";}
            if($this->e_no_serial){ echo "Il n'existe pas de groupe relié avec ce serial.<br/>";}
        }
    }
    
    public function useSerial(){
        if(isset($_POST['btn_serial'])){
            $_POST = array_map("mysql_real_escape_string", $_POST);
            $member_id = $_SESSION['member_session']['id'];
            $query = mysql_query("SELECT COUNT(*) as nb, id_team FROM team WHERE serial='".$_POST['serial']."'");
            $res = mysql_fetch_array($query);
            
            if($res['nb'] != 0){
                
                $query2 = mysql_query("SELECT COUNT(*) as nb_mber FROM team_member WHERE team_id='".$res['id_team']."' AND member_id='".$member_id."'");
                $res2 = mysql_fetch_array($query2);
                
                if($res2['nb_mber'] == 0){
                    
                    mysql_query("INSERT INTO team_member (team_id, member_id) VALUES ('".$res['id_team']."', '".$member_id."')");
                    $query3 = mysql_query("SELECT id FROM team_group WHERE name_group='Default' AND team_id='".$res['id_team']."'");
                    $res3 = mysql_fetch_array($query3);
                    mysql_query("INSERT INTO member_group (group_id, member_id) VALUES ('".$res3['id']."', '".$member_id."')");
                    
                }else{
                    $this->e_alrdy_add = true;
                }
            }else{
                $this->e_no_serial = true;
            }
        }
    }

    /*
     * List the members of current team
     * if true, only the one without any group in that team
     */
    public function listingMember($free = false){
        $result = array();
        $id_group = array();
        $id_member = array();
        $member_free = array();
        
        //Gather all members of the current team
        $query = mysql_query("SELECT member_id FROM team_member WHERE team_id='" . $_SESSION['member_session']['team'] . "'");
        $nber_rows = mysql_num_rows($query);
        while ($member = mysql_fetch_array($query)) {
                array_push($id_member, $member['member_id']);
        }

        //Gather all groups of the current team
        $query_group = mysql_query("SELECT id FROM team_group WHERE team_id='" . $_SESSION['member_session']['team'] . "'");

        while($id = mysql_fetch_array($query_group)){
            array_push($id_group, $id['id']);
        }
        //Check if at least one member exist in the current team
        if($nber_rows != 0){
            /*
             * Ask all the member
             */
            if(!$free){
                //Put in array id_member and corresponding pseudo
                foreach($id_member as $id_m){
                        $query_lst_member = mysql_query("SELECT pseudo FROM member WHERE id_member='" . $id_m . "'");
                        $rslt_lst_team = mysql_fetch_array($query_lst_member);
                        $result[$id_m] = $rslt_lst_team['pseudo'];
                    
                }
            //Return the previous table
            return $result;
            
            /*
             * Ask only the member without groupe
             */
            }else{
                //Set the query to gather member in group
                $query_member_id_group = "SELECT member_id FROM member_group WHERE group_id='" . $id_group[0] . "'";
                $i = 0;

                foreach ($id_group as $id_q) {
                    if($i != 0){
                        $query_member_id_group .= " OR group_id='" . $id_q . "'";
                    }
                    $i++;
                }

                $tab_m_g = array();
                $qry_member_in_group = mysql_query($query_member_id_group);
                while($fetch_m_g = mysql_fetch_array($qry_member_in_group))
                {
                    $tab_m_g[$fetch_m_g['member_id']] = $fetch_m_g['member_id'];
                }

                foreach($tab_m_g as $mber_id_in_group){
                    if(in_array($mber_id_in_group, $id_member)){
                        unset($id_member[array_search($mber_id_in_group, $id_member)]);
                    }
                }

                $id_psd_free = array();
                foreach($id_member as $id2){
                    $qry = mysql_query("SELECT pseudo FROM member WHERE id_member='" . $id2 . "'");
                    $res = mysql_fetch_array($qry);
                    $id_psd_free[$id2] = $res['pseudo'] ;
                }

                return $id_psd_free;
            }
            
        }
        return null;
    }

    public function listingSpecificMember($group = 'Administrateur', $ajax = false){
        $list = array();
        $res_list = array();
        $qry = mysql_query("SELECT id FROM team_group WHERE name_group='" . $group . "' AND team_id='" . $_SESSION['member_session']['team'] . "'");
        $res = mysql_fetch_array($qry);
        $group = $res['id'];

        
        $qry = mysql_query("SELECT member_id FROM member_group WHERE group_id='" . $group . "'");

        while ($row = mysql_fetch_array($qry)) {
            $list[$row['member_id']] = $row['member_id'];
        }

        foreach ($list as $value) {
            $qry = mysql_query("SELECT pseudo FROM member WHERE id_member='" . $value . "'");
            $res = mysql_fetch_array($qry);
            $res_list[$value] = $res['pseudo'] ;
        }

        if($ajax){
            foreach ($res_list as $key => $valueL) {
                echo '<option value="' . $key . '" >' . $valueL . '</option>';
            }
        }else{
            return $res_list;
        }
        

    }

    public function firedMember(){
        if(isset($_POST['btn_del_mbr'])){
            mysql_query("DELETE FROM team_member WHERE member_id='" . $_POST['member'] . "' AND team_id='" . $_SESSION['member_session']['team'] . "'");
        }
    }

    public function quitTeam(){
        if(isset($_POST['quit_team'])){
            $query = mysql_query("SELECT id FROM team_member WHERE team_id='" . $_SESSION['member_session']['team'] . "'");
            $nb_rows = mysql_num_rows($query);

            if($nb_rows == 1){
                mysql_query("DELETE FROM team WHERE id_team='" . $_SESSION['member_session']['team'] . "'");
            }
            
            mysql_query("DELETE FROM team_member WHERE team_id='" . $_SESSION['member_session']['team'] . "' AND member_id='" . $_SESSION['member_session']['id'] . "'");
        }
    }

    public function listingTeam(){
        $query = mysql_query("SELECT team_id FROM team_member WHERE member_id='" . $_SESSION['member_session']['id'] . "'");
        $nber_row = mysql_num_rows($query);
        $tab_lst_team = array();
        $i = 0;
        while($res_team = mysql_fetch_array($query)){
            $query_lst_team = mysql_query("SELECT * FROM team WHERE id_team='" . $res_team['team_id'] .  "'");
            $res_lst_team = mysql_fetch_array($query_lst_team);
            
            $tab_lst_team[$res_lst_team['id_team']] = $res_lst_team['team_name'];
//            //Session a enlever juste pour test
//            $_SESSION['member_session']['team'] = $res_lst_team['id_team'];
            $i++;
        }
        
        if($nber_row != 0){
            foreach($tab_lst_team as $key=>$value){
                echo '<a href="'.ROOT.'/dashboard?team_id=' . $key . '">' . $value . '</a><br/>';

            }
        }else{
            echo "Vous ne faites parti d'aucune equipe pour le moment.";
        }
        
    }

    public function currentTeam(){
        $query_crt_team = mysql_query("SELECT * FROM team WHERE id_team='" . $_SESSION['member_session']['team'] . "'");
        $res_crt_team = mysql_fetch_array($query_crt_team);
        return $res_crt_team['team_name'];
    }

    public function flagOfInviation(){
        $query_ti = mysql_query("SELECT * FROM team_invitation WHERE guest='" . $_SESSION['member_session']['id'] . "'");
        $nber_row = mysql_num_rows($query_ti);
        if($nber_row > 1){
            echo "Vous avez <a href=\"all_team.php\">" . $nber_row . " Invitations</a> en attente.";
        }elseif($nber_row == 1){
            echo "Vous avez <a href=\"all_team.php\">" . $nber_row . " Invitation</a> en attente.";
        }

    }

    public function receiveInvitation(){
        $query_ti = mysql_query("SELECT * FROM team_invitation WHERE guest='" . $_SESSION['member_session']['id'] . "'");
        $nber_row = mysql_num_rows($query_ti);
        if($nber_row != 0){
            while($res_q_ti = mysql_fetch_array($query_ti)){
                $query_ti_info = mysql_query("SELECT pseudo FROM member WHERE id_member='" . $res_q_ti['host'] . "'");
                $res_ti_info = mysql_fetch_array($query_ti_info);
                $query_team_name = mysql_query("SELECT team_name FROM team WHERE id_team='" . $res_q_ti['team'] . "'");
                $res_team_name = mysql_fetch_array($query_team_name);
                echo 'L\'utilisateur ' . $res_ti_info['pseudo'] . ' souhaite vous inviter dans son equipe de travail "' . $res_team_name['team_name'] . '".<br/>';
                echo '<a href="team.php?team_id=' . $res_q_ti['team'] . '&valid=true">Rejoindre</a> ou <a href="team.php?team_id=' . $res_q_ti['team'] . '&valid=false">Rejeter</a>';
            }
        }else{
            echo "Aucune invitation";
        }

    }

    public function invitationReply(){
        if(isset($_GET['team_id']) && isset($_GET['valid'])){
            mysql_query("DELETE FROM team_invitation WHERE team='" . $_GET['team_id'] . "' AND guest='" . $_SESSION['member_session']['id'] . "'");
            if($_GET['valid'] == 'true'){
                $query_team_exist = mysql_query("SELECT * FROM team_member WHERE team_id='" . $_GET['team_id'] . "' AND member_id='" . $_SESSION['member_session']['id'] . "'");
                $mysql_num_row = mysql_num_rows($query_team_exist);
                if($mysql_num_row == 0){
                    mysql_query("INSERT INTO team_member (team_id, member_id) VALUES ('" . $_GET['team_id'] . "','" . $_SESSION['member_session']['id'] . "')");
                    
                    $query4 = mysql_query("SELECT id FROM team_group WHERE name_group='Default' AND team_id='".$_SESSION['member_session']['team']."'");
                    $res4 = mysql_fetch_array($query4);
                    echo "SELECT id FROM team_group WHERE name_group='Default' AND team_id='".$_SESSION['member_session']['team']."'";
                    echo $res4['id'];
                    mysql_query("INSERT INTO member_group (group_id, member_id) VALUES ('".$res4['id']."', '".$_SESSION['member_session']['id']."')");
                    header('Location: team.php?team_id='. $_GET['team_id']);
                    exit;
                }else{
                    header('Location: all_team.php');
                    exit;
                }
                
            }else{
                header('Location: all_team.php');
                exit;
            }
        }
    }

    public function isSingle(){
        $query = mysql_query("SELECT id FROM team_member WHERE team_id='" . $_SESSION['member_session']['team'] . "'");
        $nb_rows = mysql_num_rows($query);
        if($nb_rows > 1){
            return false;
        }else{
            return true;
        }
    }
    
    public function getNote(){
        $res = mysql_fetch_array(mysql_query("SELECT contenu FROM note WHERE id_member='".$_SESSION['member_session']['id']."'"));
        return $res['contenu'];
    }
}
?>
